const fs = require('fs');
const path = require('path');
const express = require('express');
const logger = require('morgan'); // 日志
const nunjucks  = require('nunjucks'); // 模板引擎

const teacherRouter = require( './routes/teacher.js' );
const studentRouter = require( './routes/student' );
const deptRouter = require( './routes/dept' );
const courseRouter = require( './routes/course' );

const port = 8080 ;
const app = express();

// 设置模板引擎文件的后缀
app.set( 'view engine','njk' );
// 注意 __dirname 是指 app.js 文件所在目录
const viewRoot = path.resolve( __dirname, 'views' ) ;
// 设置视图文件所在的根目录
app.set( 'views' , viewRoot ); 

nunjucks.configure('views', { autoescape: true , express: app } );

app.use(logger('dev'));

app.use(express.static('public'));
app.use(express.urlencoded({ extended: false }));
app.use(express.text());
app.use(express.json());

app.get( '/hello/:name' , (req,resp)=>{
  let name = req.params.name ;
  let pathname = path.resolve( __dirname , 'public' , 'hello.html');
  let content = fs.readFileSync( pathname , 'utf-8');
  content = content.replace( '${name}' , name );
  resp.send( content );
});

app.get( '/sign/in' , (req,resp) => {
  resp.render( 'sign-in' );
});

app.post( '/sign/in' , (req,resp) => {
  let username = req.body.username ;
  let passowrd = req.body.passowrd ;
  if( !username ){
    let data = { error : '用户名不可以为空哦' };
    resp.render( 'sign-in' , data );
    return ;
  }

  if( !passowrd ){
    let data = { error : '密码不可以为空哦' };
    resp.render( 'sign-in' , data );
    return ;
  }

  resp.send( '<h1>登录成功</h1>' );
});

app.use( '/teacher' , teacherRouter );

app.use( '/student' , studentRouter );

app.use( '/dept' , deptRouter );

app.use( '/course' , courseRouter );

app.listen( port );
